import _ from 'lodash-es';
import { defineStore } from 'pinia';

const useMapStore = defineStore('storeMap', {
  state: () => ({
    initialized: [], //初始化
    mode: '2d', //二三维
    visibleLayers: new Set(), //图层是否存在
    attributeList: [], //属性
    resultCheckedStateQuery: '', //查询
    mapOnClick: null, //地图事件
  }),

  actions: {
    RESET() {
      this.initialized = [];
      this.visibleLayers = new Set();
    },

    INITIALIZE(payload) {
      this.initialized = _.uniq([...this.initialized, payload]);
    },

    CHANGE_MODE(payload) {
      this.mode = payload;
    },

    TOGGLE_LAYERS(payload) {
      const visibleLayers = new Set(this.visibleLayers);

      payload.forEach((layerId) =>
        visibleLayers.has(layerId) ? visibleLayers.delete(layerId) : visibleLayers.add(layerId),
      );
      this.visibleLayers = visibleLayers;
    },

    ATTRIBUTES_LIST_LAYER(payload) {
      if (!Object.keys(payload).length) {
        this.attributeList = [];
      } else {
        const val = new Map();
        const v1 = this.attributeList;
        const v2 = [];

        for (let i = 0; i < v1.length; i++) {
          val.set(v1[i].key, v1[i]);
        }

        if (val.has(payload.key)) {
          val.delete(payload.key);
        } else {
          val.set(payload.key, payload);
        }

        for (let value of val.values()) {
          v2.push(value);
        }

        this.attributeList = v2;
      }
    },

    SET_FUNCTION_MAP(fun) {
      this.mapOnClick = fun;
    },

    SET_CHECKED_MAP_USE(state) {
      this.resultCheckedStateQuery = state;
    },
  },
});

export default useMapStore;
